<?php

/**
 * user actions.
 *
 * @package    acca
 * @subpackage user
 * @author     Rommel M. Zamora / Sonny L. Cabali
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class userActions extends sfActions
{

	/**
	 * Executes index action
	 *
	 * @param sfRequest $request A request object
	 */
	public function executeIndex(sfWebRequest $request) {
    $this->tableColumns = sfGuardUserTable::TableColumns();
	}

  public function executeHistory(sfWebRequest $request)
  {
    $this->forward404Unless($records = UserLogsTable::getInstance()->findByUserId($request->getParameter('id')));
    return $this->renderPartial('history',array('records'=>$records));
  }

    public function executeAjaxNewForm(sfWebRequest $request) {
    	sfConfig::set('sf_web_debug', false);
        $form = new sfGuardUserForm();
        return $this->renderPartial("userForm", array("form"=>$form));
    }

    public function executeAjaxSave(sfWebRequest $request) {
    	sfConfig::set('sf_web_debug', false);

    	$sfGuardForm = $request->getParameter('sf_guard_user');
    	if(!empty($sfGuardForm)) {
    		$data = Doctrine_Core::getTable('sfGuardUser')
    		          ->findOneById($sfGuardForm['id']);
    		$form = new sfGuardUserForm($data);
    	}
    	else {
    	   	$form = new sfGuardUserForm();
    	}

        $data = $this->processForm($request, $form);
        return $this->renderText(json_encode($data));
    }

    public function executeAjaxFormEdit(sfWebRequest $request) {
        sfConfig::set('sf_web_debug', false);
        $data = Doctrine_Core::getTable('sfGuardUser')->findOneById($request->getParameter('id'));
        $form = new sfGuardUserForm($data);
        return $this->renderPartial("userForm", array("form"=>$form));
    }

  public function executeAccountHistory(sfWebRequest $request)
  {
    $this->forward404Unless($application_id = $request->getParameter('appId'));
    sfConfig::set('sf_web_debug', false);
    $this->appId = $application_id;
    $this->assignees = AssigneeTable::getAssignees($application_id);
    return $this->renderPartial('assigneeslist',array('appId'=>$this->appId,'assignees'=>$this->assignees));
  }

	protected function processForm(sfWebRequest $request, sfForm $form) {
		$form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));

		// flag
		$boolIsNew = ($form->getObject()->isNew() ? true : false );

		if ($form->isValid()) {

			$data = $form->getTaintedValues();
			$data['username'] = $data['email_address'];
			if(isset($data['is_active'])) {
			  $data['is_active'] = 1;
      }
      else {
        $data['is_active'] = 0;
      }
			$form->bind($data);
			$sfUserId = $form->save();

		    $group = new sfGuardUserGroup();
            $group->setUserId($sfUserId);
            $group->setGroupId($data['groups_list']);
            $group->save();

			// for edit mode, update password
			if(!$boolIsNew && !empty($data['password']) ) {
				$objSfUser = Doctrine_Core::getTable('sfGuardUser')
				    ->findOneById($data['id']);
				$objSfUser->setPassword($data['password']);
				$objSfUser->save();
			}

			$data_arr = array("status" => 'success',
			                  "message" => 'Data successfully saved!',
			                  "id" => $group->getUser()->getId(),
			                  "data"=>$this->getPartial('webcomponents/successNotification'));
		}
		else {
			$data_arr = array("status" => 'failed',
			                  "data" => $this->getPartial("webcomponents/errorNotification",
		                                  array('errorList'=>$form->getCustomError())));
		}

		return $data_arr;
	}

	public function executeAjaxdata(sfWebRequest $request) {
		sfConfig::set('sf_web_debug', false);
		$this->getResponse()->setContentType('application/json');
		$this->sf_guard_user = Doctrine::getTable('sfGuardUser');
		$json = $this->sf_guard_user->fetchData($request);
		return $this->renderText($json);
	}

	public function executeAjaxDelete(sfWebRequest $request) {
		sfConfig::set('sf_web_debug', false);
		$id = $request->getParameter('id', NULL);
        if(empty($id)) {
            return $this->renderText(
                 json_encode(array('status'=>'failed',
                       'message'=>'Error deleting record',
                       'data'=>$this->getPartial("webcomponents/errorNotification"))));
        }
        else {
            $obj = Doctrine_Core::getTable('sfGuardUser')
                     ->findOneById($id);

            if($obj) {
            	$obj->delete();
            	return $this->renderText(
                    json_encode(array('status'=>'success',
                          'message'=>'Successfully deleted.',
                          'data'=>$this->getPartial("webcomponents/successNotification"))));
            }
            else {
            	return $this->renderText(
                    json_encode(array('status'=>'failed',
                          'message'=>'Error deleting record.',
                          'data'=>$this->getPartial("webcomponents/errorNotification"))));
            }

        }
	}

	public function executeAjaxChangeStatus(sfWebRequest $request) {
		sfConfig::set('sf_web_debug', false);
		$id = $request->getParameter('id', NULL);
		if(empty($id)) {
			return $this->renderText(
			     json_encode(array('status'=>'failed',
			           'message'=>'Error saving.',
                       'data'=>$this->getPartial("webcomponents/errorNotification"))));
		}
		else {
			$obj = Doctrine_Core::getTable('sfGuardUser')
			         ->findOneById($id);

			if($obj) {
				if($obj->getIsActive())
				    $obj->setIsActive(false);
				else
				    $obj->setIsActive(true);

				$obj->save();

				return $this->renderText(
                    json_encode(array('status'=>'success',
                          'message'=>'Record saved.',
                          'data'=>$this->getPartial("webcomponents/successNotification"))));
			}
			else {
				return $this->renderText(
                    json_encode(array('status'=>'failed',
                          'message'=>'Error saving.',
                          'data'=>$this->getPartial("webcomponents/errorNotification"))));
			}
		}
	}

    public function executeAjaxChangeSuperAdmin(sfWebRequest $request) {
        sfConfig::set('sf_web_debug', false);
        $id = $request->getParameter('id', NULL);
        if(empty($id)) {
            return $this->renderText(
                 json_encode(array('status'=>'failed',
                       'message'=>'Error saving',
                       'data'=>$this->getPartial("webcomponents/errorNotification"))));
        }
        else {
            $obj = Doctrine_Core::getTable('sfGuardUser')
                     ->findOneById($id);

            if($obj) {
                if($obj->getIsSuperAdmin())
                    $obj->setIsSuperAdmin(false);
                else
                    $obj->setIsSuperAdmin(true);

                $obj->save();

                return $this->renderText(
                    json_encode(array('status'=>'success',
                          'message'=>'Record saved.',
                          'data'=>$this->getPartial("webcomponents/successNotification"))));
            }
            else {
                return $this->renderText(
                    json_encode(array('status'=>'failed',
                          'message'=>'Error saving.',
                          'data'=>$this->getPartial("webcomponents/errorNotification"))));
            }
        }
    }

}
